<?php

namespace App\Http\Controllers\Home\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Home\Client as ClientModel;
use Client;
use Frame;
use Tools;
use Auth;
use Illuminate\Support\Facades\DB;


class ClientController extends Controller
{
    protected $passField = [
        'chinese_name','english_name','abbreviation_name','replace_name','url','contacts','duties','sex','country_code','phone','company_phone','email','related_url','company_address','area','brief','demand','uid','assign','assign_time','share'
    ];
    protected $customer;

    public function __construct()
    {
        $this->customer = get_config_cache('customer');
    }

    public function all(Request $request)
    {
        $page = $request->input('page');

        $page_info = Tools::page_helper($page,config('base.home_limit.base_limit.render_limit'),config('base.home_limit.base_limit.limit'));

        $list = Client::getList($page_info['skip'],$page_info['limit']);

        $count = Client::getCount();

        $num = intval(ceil($count/config('base.home_limit.base_limit.limit')));

        $customer_day = $this->customer;

        return view('Home.User.Client.all',compact('list','page','num','customer_day'));
    }

    public function private(Request $request)
    {
        $page = $request->input('page');

        $page_info = Tools::page_helper($page,config('base.home_limit.base_limit.render_limit'),config('base.home_limit.base_limit.limit'));

        $opt = [
            'assign',[Auth::id()]
        ];

        # 如果上级是管理组就拥有上级和兄弟查看权限
        $belong  = json_decode(Db::table('frame')->where(['uid'=>Auth::id()])->get(),true);

        if(@$belong[0]['level']==3 && @$belong[0]['belong']!=0 ){

            $borther = json_decode(Db::table('frame')->where(['belong'=>$belong[0]['belong']])->select('uid')->get(),true);

            foreach($borther as $k=>$v){
                $borther2[] = $v['uid'];
            }

            array_push($borther2,$belong[0]['belong']);

            if($borther2){
                $opt = [
                    'assign',$borther2
                ];
            }

        }

        $list = Client::getList($page_info['skip'],$page_info['limit'],[],$opt);

        $count = Client::getCount([],$opt);

        $num = intval(ceil($count/config('base.home_limit.base_limit.limit')));

        $customer_day = $this->customer;

        return view('Home.User.Client.private',compact('list','page','num','customer_day'));
    }

    public function add(Request $request){
        if($request->isMethod('post')){
            //验证
            $this->validate(request(), [
                'chinese_name' => 'required|string',
                'english_name' => 'nullable|string',
                'abbreviation_name' => 'required|string',
                'replace_name' => 'nullable|string',
                'url' => 'nullable|string',
                'contacts' => 'required|string',
                'duties' => 'nullable|string',
                'sex' => 'integer',
                'country_code' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'phone' => ['required','integer',function ($attribute, $value, $fail) {
                    $country_code = trim(request()->input('country_code'));
                    if ($country_code){
                        $value = trim($value);
                        $client = ClientModel::where('country_code',$country_code)->where('phone',$value)->where('status',1)->first();
                        if ($client){
                            $fail(':attribute 已存在。');
                        }
                    }
                }],
                'company_phone' => 'required|integer',
                'email' => 'required|string',
                'related_url' => 'nullable|string',
                'company_address' => 'nullable|string',
                'area' => 'required|string',
                'brief' => 'required|string',
                'demand' => 'nullable|string',
                'shareTo' => 'required|integer'
            ],[],[
                'chinese_name' => '公司中文名称',
                'english_name' => '公司英文名称',
                'abbreviation_name' => '公司简称',
                'replace_name' => '替代名称',
                'url' => '公司网站地址',
                'contacts' => '公司联系人',
                'duties' => '职务',
                'sex' => '性别',
                'country_code' => '国家区号',
                'phone' => '手机',
                'company_phone' => '公司电话',
                'email' => 'Email',
                'related_url' => '其它相关网址',
                'company_address' => '公司地址',
                'area' => '所在地区',
                'brief' => '公司简介及福利',
                'demand' => '利益诉求',
                'shareTo' => '任务归属',
            ]);
            //数据库操作
            $data = [];
            foreach ($request->all() as $key => $val){
                if (!is_numeric($val)){	$val = clean($val);}
                if(in_array($key,$this->passField)){
                    $data[$key] = $val;
                }
            }

            switch (intval(request()->post('shareTo'))){
                case 1:
                    $data['assign'] = Auth::id();
                    $data['assign_time'] = strtotime('+ '.$this->customer.' day',time());
                    $data['share'] = 0;
                    break;
                case 2:
                    $data['assign'] = '';
                    $data['assign_time'] = '';
                    $data['share'] = 1;
                    break;
                case 3:
                    if ($assign = intval(request()->post('assign'))){
                        $data['assign'] = $assign;
                        $data['assign_time'] = strtotime('+ '.$this->customer.' day',time());
                        $data['share'] = 0;
                    }else{
                        $data['assign'] = '';
                        $data['assign_time'] = '';
                        $data['share'] = 1;
                    }
                    break;
                default:
                    $data['assign'] = '';
                    $data['assign_time'] = '';
                    $data['share'] = 1;
            }

            $data['uid'] = Auth::id();
            $res = ClientModel::create($data);

            return ['code'=>1];
            //返回结果
        }
        $frame = Frame::GetFrame(config('base.branch.lg.id'),config('base.level.admin'));

        $customer_day = $this->customer;

        return view('Home.User.Client.Common.add_client',compact('frame','customer_day'));
    }

    public function edit(ClientModel $obj){
        if(request() ->isMethod('post')){
            //验证
            $rules = [
                'chinese_name' => 'required|string',
                'english_name' => 'nullable|string',
                'abbreviation_name' => 'required|string',
                'replace_name' => 'nullable|string',
                'url' => 'nullable|string',
                'contacts' => 'required|string',
                'duties' => 'nullable|string',
                'sex' => 'integer',
                'country_code' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'phone' => ['required','integer',function ($attribute, $value, $fail) use($obj){
                    $country_code = trim(request()->input('country_code'));
                    if ($country_code){
                        $value = trim($value);
                        if (trim($obj->country_code.$obj->phone) != $country_code.$value){
                            $client = ClientModel::where('country_code',$country_code)->where('phone',$value)->where('status',1)->first();
                            if ($client){
                                $fail(':attribute 已存在。');
                            }
                        }
                    }
                }],
                'company_phone' => 'required|string',
                'email' => 'required|string',
                'related_url' => 'nullable|string',
                'company_address' => 'nullable|string',
                'area' => 'required|string',
                'brief' => 'required|string',
                'demand' => 'nullable|string',
                'shareTo' => 'required|integer'
            ];

            if ($obj->assign == Auth::id() && $obj->uid != Auth::id() && !Auth::user()->hasRole('admin')){
                foreach ($rules as $k => $v){
                    if ($k != 'shareTo'){
                        unset($rules[$k]);
                    }
                }
            }

            $this->validate(request(), $rules,[],[
                'chinese_name' => '公司中文名称',
                'english_name' => '公司英文名称',
                'abbreviation_name' => '公司简称',
                'replace_name' => '替代名称',
                'url' => '公司网站地址',
                'contacts' => '公司联系人',
                'duties' => '职务',
                'sex' => '性别',
                'country_code' => '国家区号',
                'phone' => '手机',
                'company_phone' => '公司电话',
                'email' => 'Email',
                'related_url' => '其它相关网址',
                'company_address' => '公司地址',
                'area' => '所在地区',
                'brief' => '公司简介及福利',
                'demand' => '利益诉求',
                'shareTo' => '任务归属',
            ]);

            //数据库操作
            foreach (request()->all() as $key => $val){
                if (!is_numeric($val)){	$val = clean($val);}
                if(in_array($key,$this->passField)){
                    $obj->$key = $val;
                }
            }

            switch (intval(request()->post('shareTo'))){
                case 1:
                    $obj->assign = Auth::id();
                    $obj->assign_time = strtotime('+ '.$this->customer.' day',time());
                    $obj->share = 0;
                    break;
                case 2:
                    $obj->assign = '';
                    $obj->assign_time = '';
                    $obj->share = 1;
                    break;
                case 3:
                    if ($assign = intval(request()->post('assign'))){
                        $obj->assign = $assign;
                        $obj->assign_time = strtotime('+ '.$this->customer.' day',time());
                        $obj->share = 0;
                    }else{
                        $obj->assign = '';
                        $obj->assign_time = '';
                        $obj->share = 1;
                    }
                    break;
                default:
                    $obj->assign = '';
                    $obj->assign_time = '';
                    $obj->share = 1;
            }

            $res = $obj->save();
            //返回结果
            return ['code'=>1];
        }

        $obj = Tools::checkDown($obj);

        $obj = Client::SetAssign($obj);

        $frame = Frame::GetFrame(config('base.branch.lg.id'),config('base.level.admin'));

        $obj->load(['user']);

        if ($obj->assign){
            if ($obj->assign == Auth::id()){
                $obj->shareTo = 1;
            }else{
                $obj->shareTo = 3;
            }
        }else{
            $obj->shareTo = 2;
        }

        $customer_day = $this->customer;

        return view('Home.User.Client.Common.edit_client',compact('obj','frame','customer_day'));
    }

    public function buy(ClientModel $obj){

        $user = Auth::user();

        $rerurn = ['code'=>0,'msg'=>'下载点不足'];

        if (intval($user->download-1) >= 0){

            $user->download = intval($user->download-1);

            $obj->download_log()->create(['uid'=>Auth::id(),'cid'=>$obj->id,'type'=>1]);

            $user->save();

            $rerurn = ['code'=>1,'msg'=>'OK'];
        }

        return $rerurn;

    }

    public function del(ClientModel $obj)
    {
        if(Auth::user()->hasAnyRole(['admin']) || Auth::id()==$obj->uid){

            $obj->status = 0;

            $res = $obj->save();

            if ($res){

                $rerurn = ['code'=>1,'msg'=>'OK'];

            }else{

                $rerurn = ['code'=>0,'msg'=>'服务器错误'];
            }
        }else{

            $rerurn = ['code'=>0,'msg'=>'没有权限'];
        }

        return $rerurn;
    }

}